<!-- home -->
<template>
  <div class="index-container">
    <van-overlay :show="showBrowserTip" @click="showBrowserTip = false">
      <img :src="openTipImg" class="width-max">
    </van-overlay>
    <div class="mainitem" v-if='conventional'>
      <div class="containers"></div>
      <div class="General-container" v-if="linkType=='99' || linkType=='100'">
        <div class="main">
          <div class="index-container" v-show="currentshow">
            <van-form :model="bookFrom">
              <div class="guidelink">
                <span @click="guidelink">查看下单指引</span>
              </div>
              <van-popup v-model="guidelinkshow" position="bottom" style="height:100%">
                <Guidelink @headleBack="activeheadleBack" @maptipsshow="maptipsshow"></Guidelink>
              </van-popup>
              <van-cell is-link title="选择配送城市" :name="bookFrom.city" :label="bookFrom.city" @click="headleSelfcity"
                class="required" />
              <van-cell is-link title="配送地址" name="area" value-class="area-text" :label="bookFrom.deliveryArea ? bookFrom.deliveryArea : '请输入XX小区/学校/超市/广场等进行定位'" @click="heanleshowDeliveryArea"
                class="required" />
              <van-popup v-model="showDeliveryArea" position="bottom" style="height:100%">
                <Map @callFather="activeSon" @maptipsshow="maptipsshow" :msg="newcenter" :city='bookFrom.city'></Map>
              </van-popup>
              <van-field v-model="bookFrom.address" input-align="right" type="textarea" rows="1" maxlength="50" autosize name="详细地址"
                label="详细地址" placeholder="XX栋XX单元XX房" class="required" @input='handleAddress(bookFrom.address)' />
              <van-cell :is-link="canChangeChannel" title="购买平台" :name="bookFrom.orderchannel" :label="bookFrom.orderchannel" @click="() => { canChangeChannel ? headleOrderchannel() : null }"
                class="required" />
              <div class="line"></div>
              <div class="cakeStyle">
                <div class="titlestyle">挑选蛋糕款式</div>
                <span style="color: #ff0000;font-size: 12px;line-height: 18px;">注：点击下方搜素栏填写购买的蛋糕名称，蛋糕款式或磅数以购买券码为准，不支持填写其他款式或磅数</span>
                <div class="filter">
                  <van-search v-model="searchcake" show-action placeholder="请输入购买的蛋糕名称" @input="headlesearchcake">
                    <template #action>
                      <div @click="onCancel">取消</div>
                    </template>
                  </van-search>
                </div>
                <!-- 款式已售罄 -->
                <p class="sold_out" v-show="showSoldOut">该款式已售罄，请挑选其他款式，或联系客服~</p>
                <ul class="cakelistgen">
                  <li v-for="(item,index) in bookFrom.cakelist" :key="index" :class="{active:(indexs2==index)}" @click="headleCakety(item,index)">
                    <div class="Unselected" :class="{active:(indexs2==index)}"></div>
                    <img :src="item.imageUrl" class="cakeimg" alt="" v-lazy="item.imageUrl">
                    <div class="cakename">{{ item.marketName }}</div>
                  </li>
                </ul>
              </div>
              <div class="addMore" v-show = "isShowAddMore">
                <p style="text-align: center" @click="addMoreList">点击查看更多款式</p>
              </div>

              <div class="nextstep" @click="nextstep(bookFrom)">下一步</div>
              <div class="WeChat">
                <concatService></concatService>
              </div>

            </van-form>
          </div>
          <div class="index-container" v-show="nextstepshow">
            <van-nav-bar
              title="熊猫不走蛋糕"
              left-text="上一步"
              left-arrow
              @click-left="preSetp"
            />
            <div class="odercake">
              <div class="odercake-item">
                <img :src="nextcakelist.imageUrl" class="cakeimg" alt="">
                <div class="cakename">{{ nextcakelist.marketName }}</div>
              </div>
            </div>
            <van-field v-model="bookFrom.username" input-align="right" maxlength="10" name="收货人姓名" label="收货人姓名" placeholder="请输入收货人姓名"
              class="required" @input='handleUsername(bookFrom.username)' />
            <van-field v-model="bookFrom.phone" input-align="right" type="digit" name="收货人电话" label="收货人电话" placeholder="请输入收货人电话"
              class="required" maxlength="11" @input='handlePhone(bookFrom.phone)' />
            <van-field v-model="bookFrom.personPhone" input-align="right" type="digit" name="下单人电话" label="下单人电话" placeholder="请输入下单人电话"
              class="required personCall" maxlength="11"  :disabled = 'isdisable'  @input='handlePersonphone(bookFrom.personPhone)' />

              <div class="checked-box">
                <van-checkbox v-model="ischecked" shape="square" @change='selectchange' icon-size="16px">与收货人一致</van-checkbox>
              </div>

            <van-cell is-link title="选择配送日期" name="datetimePicker" :label="bookFrom.extractstartTimes" @click="showPicker = true"
              class="required" />
            <van-popup v-model="showPicker" position="bottom">
              <van-datetime-picker type="date" :min-date="minDate" @confirm="onSelectStarttime" @cancel="showPicker = false" />
            </van-popup>
            <van-cell is-link title="选择配送时间" name="datetimePicker" :label="bookFrom.extractendTimes" @click="onSelectEndtime"
              class="required" />
            <van-action-sheet v-model="showPickerend" @select="onSelectordereriod">
              <div class="select-list">
                <van-radio-group v-model="bookFrom.extractendTimes">
                  <div v-for="(item,index) in filterExtractTimesList" :key="index">
                    <div v-if='item.status==0'>
                      <van-radio :name="item.time" checked-color="#ff0000" disabled>{{item.time}}
                        <span style="color: #ff0000;padding-left: 12px;">(已满,请预约其他时间)</span>
                      </van-radio>
                    </div>
                    <div v-else>
                      <van-radio :name="item.time" checked-color="#ff0000" @click="headleperiodlID(item.time)">{{item.time}}</van-radio>
                    </div>
                  </div>
                </van-radio-group>
              </div>
            </van-action-sheet>
            <van-field v-model="bookFrom.greetings" input-align="right" label="祝福语" autosize type="textarea" rows="1"
              maxlength="15" show-word-limit placeholder="请输入祝福语" :formatter="formatter" class="norequired" @input='handleGreetings(bookFrom.greetings)' />
            <van-field v-model="bookFrom.groupcode" input-align="right" type="text" name="券码" label="券码" placeholder="尝试上传卡券照片识别券码"
              class="required" @input='handleGroupcode(bookFrom.groupcode)' />
            <van-cell is-link title="试吃蛋糕" :label="bookFrom.name" @click="onClickName"
              class="required" v-if="isTryCake" />
            <van-action-sheet v-model="ordernameshow" @select="onSelectName">
              <div class="select-list">
                <van-radio-group v-model="bookFrom.name">
                  <van-radio :name="item.name" checked-color="#ff0000" v-for="item in nameList" :key="item.name"
                    @click="headleOrderName(item)">{{item.name}}</van-radio>
                </van-radio-group>
              </div>
            </van-action-sheet>
            <van-field name="stepper" label="数量" class="norequired" v-if="isTryCake">
              <template #input>
                <van-stepper v-model="bookFrom.quantity" step="1" />
              </template>
            </van-field>
            <van-field v-model="bookFrom.remarks" input-align="right" label="备注" autosize type="textarea" rows="1"
              maxlength="50" show-word-limit placeholder="请输入备注" :formatter="formatter" class="norequired" @input='handleRemarks(bookFrom.remarks)' />
            <div class="photosmain">
              <div class="title"> <em>*</em>{{qrCodeLabel}}</div>
              <div class="photos">
                <van-uploader name="uploader" ref='upload' :before-read="beforeRead" v-show="!loadingShow">
                  <img v-if="bookFrom.activeUrl" :src="bookFrom.activeUrl" class="activeImg" alt="">
                  <img v-else :src="uploadImg" class="activeImg" alt="">
                </van-uploader>
                <div class="loading" v-show="loadingShow">
                  <van-loading size="24px" type='spinner' color="#fcd600"></van-loading>
                </div>
              </div>
            </div>
            <div class="submit" @click="orderSumbit(bookFrom)">提 交</div>
            <div class="WeChat">
              <concatService></concatService>
            </div>
          </div>
        </div>
      </div>
      <div class="group-container" v-else>
        <div class="guidelink">
          <span @click="guidelink">查看下单指引</span>
        </div>
        <van-popup v-model="guidelinkshow" position="bottom" style="height:100%">
          <Guidelink @headleBack="activeheadleBack" @maptipsshow="maptipsshow"></Guidelink>
        </van-popup>
        <div class="main">
          <div class="title">{{ linkName }}</div>
          <ul class="cakelist">
            <li v-for="(item,index) in bookFrom.cakelist" :key="index" :class="{active:(indexs==index)}" v-if="linkType=='2' || linkType=='3' || linkType=='4' || linkType=='5' || linkType=='98'"
              @click="headleCake(item,index)">
              <div class="Unselected" :class="{active:(indexs==index)}"></div>
              <img :src="item.imageUrl" class="cakeimg" alt="" v-lazy="item.imageUrl">
              <div class="cakename">{{ item.marketName }}</div>
            </li>
            <li v-for="(item,index) in bookFrom.cakelist" :key="index" :class="{active:(indexs==index)}" v-if="linkType=='1' || linkType=='6'">
              <!-- <div class="Unselected" :class="{active:(indexs==index)}" ></div> -->
              <img :src="item.imageUrl" class="cakeimg" alt="" v-lazy="item.imageUrl">
              <div class="cakename">{{ item.marketName }}</div>
            </li>
          </ul>
        </div>
        <van-form :model="bookFrom">
          <van-cell is-link title="选择配送城市" :name="bookFrom.city" :label="bookFrom.city" @click="headleSelfcity" class="required" />
          <van-cell is-link title="配送地址" value-class="area-text"  name="area" :label="bookFrom.deliveryArea ? bookFrom.deliveryArea : '请输入XX小区/学校/超市/广场等进行定位'" @click="heanleshowDeliveryArea(bookFrom.city)"
            class="required" />
          <van-popup v-model="showDeliveryArea" position="bottom" style="height:100%">
            <Map @callFather="activeSon" @maptipsshow="maptipsshow" :msg="newcenter" :city='bookFrom.city'></Map>
          </van-popup>
          <van-field v-model="bookFrom.address" input-align="right" name="详细地址" label="详细地址" placeholder="XX栋XX单元XX房"
            autosize type="textarea" rows="1" maxlength="50" show-word-limit :formatter="formatter" class="required"
            @input='handleAddress(bookFrom.address)' />
          <van-field v-model="bookFrom.username" input-align="right" name="收货人姓名" label="收货人姓名" placeholder="请输入收货人姓名"
            autosize rows="1" maxlength="10" class="required" @input='handleUsername(bookFrom.username)' />
          <van-field v-model="bookFrom.phone" input-align="right" type="number" name="收货人电话" label="收货人电话" placeholder="请输入收货人电话"
            maxlength='11' class="required" @input='handlePhone(bookFrom.phone)' />
            <van-field v-model="bookFrom.personPhone" input-align="right" type="digit" name="下单人电话" label="下单人电话" placeholder="请输入下单人电话"
              class="required personCall" maxlength="11"  :disabled = 'isdisable'  @input='handlePersonphone(bookFrom.personPhone)' />
              <div class="checked-box">
                <van-checkbox v-model="ischecked" shape="square" @change='selectchange' icon-size="16px">与收货人一致</van-checkbox>
              </div>
          <van-cell is-link title="选择配送日期" name="datetimePicker" :label="bookFrom.extractstartTimes" @click="showPicker = true"
            class="required" />
          <van-popup v-model="showPicker" position="bottom">
            <van-datetime-picker type="date" :min-date="minDate" @confirm="onSelectStarttime" @cancel="showPicker = false"
              class="required" />
          </van-popup>
          <van-cell is-link title="选择配送时间" name="datetimePicker" :label="bookFrom.extractendTimes" @click="onSelectEndtime"
            class="required" />
          <van-action-sheet v-model="showPickerend" @select="onSelectordereriod">
            <div class="select-list">
              <van-radio-group v-model="bookFrom.extractendTimes">
                <div v-for="(item,index) in extractTimesList" :key="index">
                  <div v-if='item.status==0'>
                    <van-radio :name="item.time" checked-color="#ff0000" disabled>{{item.time}}
                      <span style="color: #ff0000;padding-left: 12px;">(已满,请预约其他时间)</span>
                    </van-radio>
                  </div>
                  <div v-else>
                    <van-radio :name="item.time" checked-color="#ff0000" @click="headleperiodlID(item.time)">{{item.time}}</van-radio>
                  </div>
                </div>
              </van-radio-group>
            </div>
          </van-action-sheet>
          <van-cell :is-link="canChangeChannel" title="购买平台" :name="bookFrom.orderchannel" :label="bookFrom.orderchannel" @click="canChangeChannel ? headleOrderchannel() : ''"
            class="required" />
          <van-field v-model="bookFrom.greetings" input-align="right" label="祝福语" autosize type="textarea" rows="1"
            maxlength="15" show-word-limit placeholder="请输入祝福语" :formatter="formatter" class="norequired" @input='handleGreetings(bookFrom.greetings)' />
          <van-field v-model="bookFrom.groupcode" input-align="right" type="text" name="券码" label="券码" placeholder="尝试上传卡券照片识别券码"
            class="required" @input='handleGroupcode(bookFrom.groupcode)' />
          <van-field v-model="bookFrom.remarks" input-align="right" label="备注" autosize type="textarea" rows="1"
            maxlength="50" show-word-limit placeholder="请输入备注" :formatter="formatter" class="norequired" @input='handleRemarks(bookFrom.remarks)' />
          <div class="photosmain">
            <div class="title"><em>*</em>{{qrCodeLabel}}</div>
            <div class="photos">
              <van-uploader name="uploader" ref='upload' :before-read="beforeRead" v-show="!loadingShow">
                <img v-if="bookFrom.activeUrl" :src="bookFrom.activeUrl" class="activeImg" alt="">
                <img v-else :src="uploadImg" class="activeImg" alt="">
              </van-uploader>
              <div class="loading" v-show="loadingShow">
                <van-loading size="24px" type='spinner' color="#fcd600"></van-loading>
              </div>
            </div>
          </div>
          <div class="submit" @click="orderSumbit(bookFrom)">提 交</div>
        </van-form>
      </div>
      <van-overlay :show="submitshow" @click="submitshow=false">
        <div class="wrapper" @click.stop>
          <div class="wrapper-top">
            <div class="wrapper-left">
              <img :src="selsumbit" alt="">
            </div>
            <div class="wrapper-right">
                <h3>主人，我们会第一时间为您下单，下单后将有短信发至收货人手机</h3>
                <p class="c-f53f3f">魔术，鲜花等增值服务，请点击升级服务！</p>
                <p class="c-999 lh-16">如有问题，0752-5201314客服热线将向您致电，请注意接听。感谢您的信任与支持！</p>
            </div>
          </div>
          <div class="wrapper-bottom">
            <div @click="watchorder">查看订单</div>
            <div class="c-007aff" @click="upgradeService">升级服务</div>
          </div>
        </div>
      </van-overlay>
      <van-overlay :show="maptipsshow" @click="headlemaptipsshow">
        <div class="wrappermap" @click.stop>
          <div class="wrapper-maptop">
            <div class="tips">{{tips}}</div>
            <concatService></concatService>
          </div>
        </div>
      </van-overlay>
      <van-overlay :show="DeliveryAreashow" @click="headleDeliveryAreashow">
        <div class="wrappermap" @click.stop style="height: 68px;">
          <div class="wrapper-maptop">
            <div class="tips">{{tips}}</div>
          </div>
        </div>
      </van-overlay>
      <!-- <van-dialog v-model="grouprangeshow" title="请选择在团购价内的产品" show-cancel-button confirmButtonText="在范围内" @confirm="groupnext"
        cancelButtonText="重新选择"></van-dialog> -->
    </div>
    <div class="mainitemabnormal" v-if='abnormal'>
      <van-overlay :show="maptipsshow">
        <div class="wrappermap" @click.stop>
          <div class="wrapper-maptop">
            <div class="tips">{{tipsno}}</div>
            <concatService ></concatService>
          </div>
        </div>
      </van-overlay>
    </div>
    <div class="mainitemabnormal" v-if='goodabnormal'>
      <van-overlay :show="maptipsshow">
        <div class="wrappermap" @click.stop>
          <div class="wrapper-maptop">
            <div class="tips">该链接无商品，请联系客服</div>
            <concatService ></concatService>
          </div>
        </div>
      </van-overlay>
    </div>
    <!-- 请挑选蛋糕款式 -->
    <van-dialog v-model="showstyle" :showConfirmButton='false'>
      <p style="text-align: center;">请-搜索-挑选蛋糕款式</p>
      <p>
        <div class="showstyleBtn" @click="handleshowstyleBtn">
          确认
        </div>
      </p>
    </van-dialog>
    <!-- 提交后出现加载按钮 -->
    <van-dialog v-model="loadingstyleshow" class="loadingstyle" :showConfirmButton='false'>
      <div class="loadingstyle">
        <van-loading size="36px" type="spinner" color="#fcd600" vertical>数据提交中...</van-loading>
      </div>
    </van-dialog>

    <div class="teepTop" @click="handtoTop" v-if="addStartNum > 9">
      <van-icon name="arrow-up" size="25"/>
    </div>

    <van-action-sheet v-model="orderchannelshow" @select="onSelectorderchannel">
      <div class="select-list">
        <van-search v-model="orderChannelKeyword" placeholder="请输入搜索关键词"/>
        <van-radio-group v-model="bookFrom.orderchannel">
        <div v-for="(item, i) in channelList" :key="`${item.value}${i}`">
          <van-radio v-show="showChannelItem(item)" :name="item.value" checked-color="#ff0000" 
            @click="headleOrderchannelID(item)">{{item.value}}</van-radio>
        </div>
        </van-radio-group>
      </div>
    </van-action-sheet>

    <van-action-sheet v-model="cityshow" title="配送城市" style="height:50%">
      <div class="address">
        <van-radio-group v-model="bookFrom.city">
          <van-radio :name="item.deptName" checked-color="#ff0000" v-for="item in filterCityList" :key="item.id"
            @click="onSelectaddress(item)">{{ item.deptName }}</van-radio>
        </van-radio-group>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
  import area from '@/api/area.js'
  import upload from '@/assets/image/upload.png'
  import openTipImg from '@/assets/image/open-tip.png'
  import selsumbit from '@/assets/image/selsumbit.png'
  import Unselected from '@/assets/image/Unselected.png'
  import Compressor from 'image-compressor.js';
  import { Dialog, Toast} from 'vant'
  import Map from '@/components/map'
  import Guidelink from '@/components/guidelink'
  import { trigger as triggerTip } from '@/components/tipDialog/tip'
  import {
    getByIdForCache,
    getGoodsListByName,
    getSelfDelivery,
    submitOrder,
    getChannelByDeptId,
    getisRange,
    getpreSubmitOrder,
    Getupload,
    setCookie,
    getInsideChannel,
  } from '@/api/index'
  export default {
    components: {
      Map,
      Unselected,
      Guidelink,
    },
    data() {
      return {
        uploadImg: upload,
        showSoldOut: false, // 显示售罄字段
        ischecked: false, //收货人是否选择
        isdisable: false, //是否可读性
        conventional: false,
        abnormal: false,
        goodabnormal: false,
        showBrowserTip: false,
        selsumbit,
        openTipImg,
        tips: '',
        linkType: '',
        linkName: '',
        selfmentionList: '',
        selfcity: [], //自提城市
        indexs: -1,
        indexs2: -1,
        center: [116.42792, 39.902896], //经度+纬度
        minDate: new Date(),
        show: false,
        showstyle: false,
        addressshow: false,
        cityshow: false,
        orderchannelshow: false,
        ordernameshow: false,
        showPicker: false,
        showPickerend: false,
        showDeliveryArea: false,
        maptipsshow: false,
        DeliveryAreashow: false,
        nextcakelist: '', //通用蛋糕链接
        location: '',
        deliverymethodlist: [{
            name: '自提',
            deliveryType: 1
          },
          {
            name: '送货上门',
            deliveryType: 2
          }
        ],
        orderchannelList: [],
        nameList: [{"name":"慕斯切片3*3cm"},{"name":"慕斯切片4*4cm"},{"name":"米数蛋糕（米）"},{"name":"定制蛋糕"}
        ,{"name":"常规蛋糕"},{"name":"DIY蛋糕"},{"name":"杯子蛋糕"},{"name":"结存蛋糕"}],
        showArea: false,
        deptId: '',
        areaList: {}, // 数据格式见 Area 组件文档
        bookFrom: {
          showMore: false,
          skuInfos: [],
          cakelist: [],
          username: '',
          phone: '',
          greetings: '',
          groupcode: '',
          remarks: '',
          deliverymethod: '',
          areavalue: '',
          address: '',
          city: '',
          selfDeliveryId: '', //自提地点的ID
          orderchannel: '',
          extractstartTimes: '',
          extractendTimes: '',
          activeUrl: '',
          deliveryArea: '',
          addressDetail: '',
          longitude: '',
          latitude: '',
          cityname: '',
          personPhone: '', // 下单人电话号
          name: '',
          quantity: ''
        },
        orderID: '',
        submitshow: false,
        // 通用链接
        nextstepshow: false,
        currentshow: true,
        searchcake: '',
        extractTimesList: [], // 配送时间段
        deliveryWay: '',
        cityname: '',
        base64Image: '',
        loadingShow: false,
        guidelinkshow: false,
        loadingstyleshow: false,
        newcenter: [],
        tipsno: '',
        linkchannel: '',
        isShowAddMore: false,
        newArrayCakeList: [], //原始数据无法改变 只为了记录原来数组的长度
        addStartNum: 9, // 开始截取的长度
        addStep: 9, //每一次增加的长度
        time: 0,
        orderChannelKeyword: '',
        canChangeChannel: true,
      }
    },
    computed: {
      isTryCake() {
        return this.bookFrom.skuInfos.length >0 && this.bookFrom.skuInfos[0].skuId==3312275747552256
      },
      channelList() {
        return this.orderchannelList ? this.orderchannelList.sort((a, b) => {
          return a.value === '抖音' ? -1 :1
        }) : []
      },
      filterCityList() {
        return this.selfcity ?
          this.selfcity.filter(item => item.deptName !== '其它市' && item.deptName !== '测试专用') : []
      },
      qrCodeLabel() {
        const channelLabelMap = {
          '615': '卡券照片（电子码/二维码的截图）',
          '734': '卡券照片（电子码/二维码的截图）',
          '4748': '团购卷码的截图',
          '10505': '团购卷码的截图',
        }
        return channelLabelMap[this.linkchannel] || '卡券照片（电子码/二维码的截图）'
      },
      needBeforeThreeDay() {
        const cakeInfo = this.bookFrom.skuInfos && this.bookFrom.skuInfos[0]
        return cakeInfo && cakeInfo.marketName.includes('提前3天')
      },
      filterExtractTimesList() {
        if (this.needBeforeThreeDay) {
          return this.extractTimesList.filter(item => {
            const startDate = this.dayjs(this.bookFrom.extractstartTimes + ' ' + item.time.slice(0, 8))
            const afterThreeDayDate = this.dayjs().add(3, 'day')
            return startDate.unix() >= afterThreeDayDate.unix()
          })
        } else {
          return this.extractTimesList
        }
        
      }
    },
    created() {
      // _czc.push('_setCustomVar','提交统计','直接跳出')
      // _czc.push('_setCustomVar','提交统计','提交成功')
        let timer = setInterval( () => {
        if(localStorage.getItem('isbettenStart')){
          this.time += 5;
          localStorage.setItem('times', this.time)
          // _czc.push('_setCustomVar','时间统计','逗留时间',this.time)
        }else{
          localStorage.setItem('times', 0)
          localStorage.setItem('isbettenStart', true)
        }
      },5000)
    },

    async mounted() {
      // 操作变量确定blean值
      if (location.href.indexOf("#reloaded") == -1) {
        location.href = location.href + "#reloaded";
        location.reload();
      }
      this.linkType = this.$route.query.type;
      this.linkchannel = this.$route.query.channel;
      if(this.linkType) {
        this.linkType = this.linkType.replace('#', '').replace('reloaded', '');
      }
      if(this.linkchannel) {
        this.linkchannel = this.linkchannel.replace('#', '').replace('reloaded', '');
      }
      this.areaList = area;

      if (this.linkchannel) {
        this.getChannelByDeptId().then(() => {
          if (this.orderchannelList) {
            this.orderchannelList.forEach(channel => {
              if (this.linkchannel == channel.id) {
                this.bookFrom.orderchannel = channel.value;
                sessionStorage.setItem('orderchannel', channel.value)
              }
            })
          }
        })

        this.bookFrom.channelId = this.linkchannel;
        sessionStorage.setItem('channelId', this.bookFrom.channelId)
      }

      if (sessionStorage.getItem('city')) {
        this.bookFrom.city = sessionStorage.getItem('city')
      } else {
        await this.showCityInfo();
      }
      if(sessionStorage.getItem('isShowIdentical') >0){
        this.ischecked = sessionStorage.getItem('isShowIdentical')
        this.isdisable = true
      }else{
        this.isdisable = false
        this.ischecked = false
      }
      if (sessionStorage.getItem('deptId')) {
        this.deptId = sessionStorage.getItem('deptId')
      }
      if (sessionStorage.getItem('personphone')){
        this.bookFrom.personPhone = sessionStorage.getItem('personphone')
      }
      if (sessionStorage.getItem('deliveryArea')) {
        this.bookFrom.deliveryArea = sessionStorage.getItem('deliveryArea')
      }

      if (sessionStorage.getItem('address')) {
        this.bookFrom.address = sessionStorage.getItem('address')
      }

      if (sessionStorage.getItem('username')) {
        this.bookFrom.username = sessionStorage.getItem('username')
      }

      if (sessionStorage.getItem('phone')) {
        this.bookFrom.phone = sessionStorage.getItem('phone')
      }

      if (sessionStorage.getItem('longitude')) {
        this.bookFrom.longitude = sessionStorage.getItem('longitude')
      }
      if (sessionStorage.getItem('latitude')) {
        this.bookFrom.latitude = sessionStorage.getItem('latitude')
      }
      if (sessionStorage.getItem('extractstartTimes')) {
        this.bookFrom.extractstartTimes = sessionStorage.getItem('extractstartTimes')
      }

      if (sessionStorage.getItem('extractendTimes')) {
        this.bookFrom.extractendTimes = sessionStorage.getItem('extractendTimes')
      }
      if (sessionStorage.getItem('channelId')) {
        this.bookFrom.channelId = sessionStorage.getItem('channelId')
      }
      if (sessionStorage.getItem('orderchannel')) {
        this.bookFrom.orderchannel = sessionStorage.getItem('orderchannel')
      }
      if (sessionStorage.getItem('greetings')) {
        this.bookFrom.greetings = sessionStorage.getItem('greetings')
      }
      if (sessionStorage.getItem('groupcode')) {
        this.bookFrom.groupcode = sessionStorage.getItem('groupcode')
      }
      if (sessionStorage.getItem('remark')) {
        this.bookFrom.remarks = sessionStorage.getItem('remark')
      }
      if (sessionStorage.getItem('activeUrl')) {
        this.bookFrom.activeUrl = sessionStorage.getItem('activeUrl')
      }
      if (sessionStorage.getItem('indexs2')) {
        this.indexs2 = sessionStorage.getItem('indexs2')
      }
      if (sessionStorage.getItem('indexs')) {
        this.indexs = sessionStorage.getItem('indexs')
      }
      // 开始获取列表长度
      this.getByIdForCacheList(() => {
        if (sessionStorage.getItem('bookFrom.cakelist')) {
          this.bookFrom.cakelist = JSON.parse(sessionStorage.getItem('bookFrom.cakelist'))
          if(this.bookFrom.cakelist.length > 9){
            this.newArrayCakeList= this.bookFrom.cakelist
            this.isShowAddMore = true
            this.bookFrom.cakelist =this.newArrayCakeList.slice(0,this.addStartNum)
          }
        }
        if (sessionStorage.getItem('bookFrom.skuInfos')) {
          this.bookFrom.skuInfos = JSON.parse(sessionStorage.getItem('bookFrom.skuInfos'))
        }
        if (sessionStorage.getItem('nextcakelist')) {
          this.nextcakelist = JSON.parse(sessionStorage.getItem('nextcakelist'))
        }
      })

      this.canChangeChannel = !this.linkchannel
    },

    methods: {
      handtoTop(){
        var timer = setInterval(function(){
            let osTop = document.documentElement.scrollTop || document.body.scrollTop;
            let ispeed = Math.floor(-osTop / 5);
            document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
            this.isTop = true;
            if(osTop === 0){
              clearInterval(timer);
            }
          },30)
      },
      // 是不选择勾选
      selectchange(){
        this.ischecked ?  this.isdisable = true : this.isdisable = false
        if(this.ischecked){
          this.bookFrom.personPhone = this.bookFrom.phone
        }
        sessionStorage.setItem('personphone', this.bookFrom.phone)
        sessionStorage.setItem('isShowIdentical',this.ischecked? 1:-1)
      },
      changeHttpImageUrl(httpUrl){
        var target = window.location.protocol === 'https:' ? 'https://groupbuy.xiongmaodangao.com/': 'http://groupbuy.xiongmaodangao.com/';
        return httpUrl.replace('http://oss.xiongmaodangao.com/', target)
      },
      changeHttpImageUrlWithArray(data){
        var that = this;
        data.forEach(item=>{
          item.imageUrl = that.changeHttpImageUrl(item.imageUrl);
        });
        return data;
      },

      showCityInfo() {
        return new Promise((resolve) => {
          let that = this;
          // 失败 启用 ip定位
          AMap.plugin('AMap.CitySearch', function() {
            var citySearch = new AMap.CitySearch();
            citySearch.getLocalCity(function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // 查询成功，result即为当前所在城市信息
                console.log('通过ip获取当前城市：', result)
                var cityinfo = result.city;
                that.bookFrom.city = cityinfo;
                getSelfDelivery({
                  deliveryWay: that.deliveryWay
                }).then(res => {
                  that.selfcity = res.data;
                  that.selfcity.map(item => {
                    if (item.deptName == cityinfo) {
                      that.deptId = item.id;
                      sessionStorage.setItem('deptId', item.id);
                      sessionStorage.setItem('city', item.deptName);
                    }
                  })
                }).finally(() => {
                  resolve()
                })
              } else {
                console.log('result', status)
                resolve()
              }
            })
          })
        })
      },
      // 公共部分---------------------------------------------------
      headleSelfcity() {
        getSelfDelivery({
          deliveryWay: this.deliveryWay
        }).then(res => {
          this.selfcity = res.data
          if (this.selfcity) {
            this.cityshow = true;
            this.newcenter = [];
          } else {
            this.tips = '当前配送城市为空，请联系客服'
            this.cityshow = false
            this.DeliveryAreashow = true
          }
        })
      },
      handlemethod() {
        this.bookFrom.city = '';
        this.bookFrom.address = '';
        this.bookFrom.deliveryArea = '';
        this.bookFrom.orderchannel = ''
      },
      // 所有的空格验证
      formatter(value) {
        return value.replace(/\s+/g, '');
      },
      changeList () {
          this.isShowAddMore = true
          this.newArrayCakeList = this.bookFrom.cakelist
          this.bookFrom.cakelist = this.newArrayCakeList.slice(0, 9)
      },
      getByIdForCacheList(callback) {
        //根据订单ID获取蛋糕详情
        const params = {
          id: this.$route.query.id,
          cityId: sessionStorage.getItem('deptId')
        }
        getByIdForCache(params)
          .then(res => {
            if (res.code == '200') {
              if(this.linkType === undefined || this.linkType === null || this.linkType === '') {
                this.linkType = res.data.linkType
              }
              this.linkName = res.data.linkName
              this.bookFrom.cakelist = this.changeHttpImageUrlWithArray(res.data.list);
              // 开始处理蛋糕的长度
              if(this.bookFrom.cakelist.length > 9){
                this.changeList()
              }
              if (res.data.linkType == 99 || res.data.linkType == 100) {
                if (this.$route.query.type == '6' || this.$route.query.type == '1') {
                  var skuIdslist = []
                  this.bookFrom.cakelist.map(child => {
                    skuIdslist.push({
                      skuId: child.skuId,
                      imgUrl: this.changeHttpImageUrl(child.imageUrl),
                      marketName: child.marketName
                    })
                  })
                  this.bookFrom.skuInfos = skuIdslist
                }
                this.conventional = true;
                this.abnormal = false;
              } else {
                if (this.bookFrom.cakelist && this.bookFrom.cakelist.length) {
                  if (this.$route.query.type == '6' || this.$route.query.type == '1') {
                    var skuIdslist = []
                    this.bookFrom.cakelist.map(child => {
                      skuIdslist.push({
                        skuId: child.skuId,
                        imgUrl: this.changeHttpImageUrl(child.imageUrl),
                        marketName: child.marketName
                      })
                    })
                    this.bookFrom.skuInfos = skuIdslist
                  }
                  this.conventional = true;
                  this.abnormal = false;
                  this.goodabnormal = false
                } else {
                  this.conventional = false;
                  this.abnormal = true;
                  this.tipsno = res.msg;
                  this.maptipsshow = true;
                  this.goodabnormal = true
                }
              }
            } else {
              this.conventional = false;
              this.abnormal = true
              this.tipsno = res.msg;
              this.maptipsshow = true;
            }
            if(callback) {
              callback();
            }
          })
          .catch(() => {})
      },
      heanleshowDeliveryArea(item) {
        if (this.deptId == '') {
          this.$toast({
            overlay: true,
            message: '请先选择配送城市',
            duration: 2000
          })
        } else {
          var mapObj = new AMap.Map("containers", {
            resizeEnable: true,
          });
          this.getMapaddress(this.bookFrom.city, mapObj)
        }
      },
      getMapaddress(name, mapObj) {
        var MSearch;
        mapObj.plugin(
          ["AMap.PlaceSearch"],
          () => {
            MSearch = new AMap.PlaceSearch({
              //构造地点查询类
              city: '' //城市
            });
            AMap.event.addListener(MSearch, "complete", this.keywordSearch_CallBack) //返回地点查询结果
            MSearch.search(name); //关键字查询
          }
        );
      },
      keywordSearch_CallBack(data) {
        var mapObj = new AMap.Map("containers", {
          resizeEnable: true,
        });
        var poiArr = data.poiList.pois
        var resultCount = poiArr.length
        this.poiArr = poiArr; //左边要渲染的数据
        this.newcenter = [poiArr[0].location.lng, poiArr[0].location.lat];
        // console.log(this.newcenter, 'this.newcenter')
        this.showDeliveryArea = true;
      },

      headleOrderchannel() {
        //购买平台
        if (this.linkType == '100') {
          this.headleInsideChannel()
        } else {
          if (this.deptId == '') {
            this.$toast({
              overlay: true,
              message: '请先选择配送城市',
              duration: 2000
            })
          } else {
            this.getChannelByDeptId()
            this.orderchannelshow = true
          }
        }
      },
      getChannelByDeptId() {
        const params = {
          deptId: this.deptId
        }
        return getChannelByDeptId(params).then(res => {
          this.orderchannelList = (res.data || []).filter(item => item.id != 615 && item.id != 104)
          if (!this.orderchannelList || !this.orderchannelList.length) {
            this.tips = '当前该购买平台为空，请联系客服'
            this.DeliveryAreashow = true
          }
        })
      },
      headleInsideChannel() {
        //购买平台
        getInsideChannel('').then(res => {
          this.orderchannelList = res.data || [];
          if (this.orderchannelList) {
            this.orderchannelshow = true
          } else {
            this.tips = '当前该购买平台为空，请联系客服'
            this.DeliveryAreashow = true
          }
        })
      },
      headleOrderchannelID(item) {
        //获取渠道ID
        this.bookFrom.channelId = item.id;
        sessionStorage.setItem('channelId', this.bookFrom.channelId)
        sessionStorage.setItem('orderchannel', this.bookFrom.orderchannel)
        this.orderchannelshow = false
      },
      onClickName(item) {
        this.ordernameshow = true;
      },
      headleOrderName(item) {
        //试吃蛋糕
        this.bookFrom.name = item.name;
        sessionStorage.setItem('name', this.bookFrom.name)
        this.ordernameshow = false
      },
      activeSon(e) {
        //地图返回
        // console.log(e)
        this.showDeliveryArea = false
        this.location = [e.location.lng, e.location.lat].join(',')
        getisRange({
          location: this.location,
          deptId: this.deptId,
          cityName: this.bookFrom.city,
        }).then(res => {
          let code = res.code
          if (code == 200) {
            this.bookFrom.cityname = this.bookFrom.city
            this.bookFrom.deliveryArea = e.name
            this.bookFrom.longitude = e.location.lng //经度
            this.bookFrom.latitude = e.location.lat //纬度
            sessionStorage.setItem('deliveryArea', this.bookFrom.deliveryArea)
            sessionStorage.setItem('longitude', this.bookFrom.longitude)
            sessionStorage.setItem('latitude', this.bookFrom.latitude)
            // console.log(this.bookFrom)
          } else if (code == 400) {
            this.tips = res.msg;
            this.maptipsshow = true
          }
        })
      },
      headlemaptipsshow() {
        //不在配送地址内
        this.maptipsshow = false
      },
      headleDeliveryAreashow() {
        //不在配送范围内
        this.DeliveryAreashow = false
        this.bookFrom.extractendTimes = ''
      },
      onSelectaddress(item) {
        //配送范围
        // console.log(item)
        this.deptId = item.id;
        this.cityshow = false;
        this.bookFrom.address = '';
        this.bookFrom.deliveryArea = '';
        this.bookFrom.orderchannel = ''
        this.bookFrom.extractstartTimes = '';
        this.bookFrom.extractendTimes = '';
        this.newcenter = [];
        sessionStorage.setItem('deptId', item.id)
        sessionStorage.setItem('city', item.deptName)
        if (this.$route.query.channel !== null) {
          this.getChannelByDeptId().then(() => {
            if (this.orderchannelList && this.orderchannelList.length) {
              this.orderchannelList.forEach(channel => {
                if (this.linkchannel == channel.id) {
                  this.bookFrom.orderchannel = channel.value;
                  sessionStorage.setItem('orderchannel', channel.value)
                }
              })
              this.bookFrom.channelId = this.linkchannel;
              sessionStorage.setItem('channelId', this.bookFrom.channelId)
            }
          })
        }
      },
      onSelectorderchannel(values) {
        //购买平台
        this.bookFrom.orderchannel = values.map(item => item.name).join('/')
        this.orderchannelshow = false
      },
      onSelectName(values) {
        //购买平台
        this.bookFrom.name = values.map(item => item.name).join('/')
        this.ordernameshow = false
      },
      onSelectordereriod(values) {
        this.showPickerend = false
      },
      headleperiodlID(item) {
        this.bookFrom.extractendTimes = item
        this.showPickerend = false;
        sessionStorage.setItem('extractendTimes', this.bookFrom.extractendTimes)
      },
      onChangend() {

      },
      onSelectStarttime(time) {
        let nowDate = new Date()
        nowDate = this.dayjs(nowDate)
          .format('YYYY-MM-DD')
          .toString()
        const selectTime = this.dayjs(time)
          .format('YYYY-MM-DD')
          .toString()
        this.bookFrom.extractstartTimes = selectTime
        sessionStorage.setItem('extractstartTimes', this.bookFrom.extractstartTimes)
        this.showPicker = false
        this.bookFrom.extractendTimes = ''
        if (this.deptId == '') {
          this.$toast({
            overlay: true,
            message: '请选择配送城市',
            duration: 2000
          })
          this.bookFrom.extractstartTimes = ''
          return false

        } else if (this.bookFrom.longitude == '' && this.bookFrom.latitude == '') {
          this.$toast({
            overlay: true,
            message: '请选择配送地址',
            duration: 2000
          })
          this.bookFrom.extractstartTimes = ''
          return false
        } else {
          let startTime, endTime;
          startTime = this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD")
            .toString();
          endTime = this.dayjs(
              this.bookFrom.extractstartTimes
            )
            .format("YYYY-MM-DD")
            .toString();

          var time1 = Date.parse(
            startTime
          );
          var time2 = Date.parse(
            endTime
          );
          //讲两个时间相减，求出相隔的天数
          var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
          // 抖音和视频号限制为180天
          if (this.linkchannel === '10505' || this.linkchannel === '4748'){
            if (dayCount > 180) {
              this.$toast({
                overlay: true,
                message: "时间间隔不可超过180天",
                duration: 2000
              });
              this.bookFrom.extractstartTimes = ''
            }
          }else {
            if (dayCount > 31) {
              this.$toast({
                overlay: true,
                message: "时间间隔不可超过31天",
                duration: 2000
              });
              this.bookFrom.extractstartTimes = ''
            }
          }
        }
      },
      onSelectEndtime() {
        var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
        if (this.bookFrom.extractstartTimes == '') {
          this.$toast({
            overlay: true,
            message: '请选择配送日期',
            duration: 2000
          })
          this.bookFrom.extractendTimes = ''
          return false
        } else {
          const params = {
            deliveryDate: this.bookFrom.extractstartTimes,
            selfDeliveryId: this.bookFrom.selfDeliveryId,
            cityName: this.bookFrom.cityname,
            longitude: this.bookFrom.longitude, //经度
            latitude: this.bookFrom.latitude, //纬度
            deptId: this.deptId,
          }
          this.extractTimesList = []
          getpreSubmitOrder(params).then(res => {
            if (res.code == '200') {
              // console.log(res)
              this.extractTimesList = res.data;
              if (this.extractTimesList) {
                this.showPickerend = true
              } else {
                this.$toast({
                  overlay: true,
                  message: '该日期已预约完，请选择其他日期',
                  duration: 2000
                })
              }
            } else {

              this.tips = res.msg
              this.DeliveryAreashow = true
              this.bookFrom.extractendTimes = ''
            }
          })
        }
      },
      beforeRead(file) {
        this.bookFrom.activeUrl = ''
        var that = this;
        that.decodeQrCode(file).then(res => {
          that.$notify({ type: 'success', message: '券码识别成功' });
          that.bookFrom.groupcode = res;
          that.handleGroupcode(res);
        }).catch(err => {
          triggerTip({show: true, title: '', content: '二维码识别失败，请手动输入券码，或联系客服'})
        }).finally(() => {
          that.getBase64(file);
        })
      },
      /*识别二维码*/
      decodeQrCode(file){
        return new Promise((resolve, reject) => {
          var that = this;
          var url = null;
          if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
          } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
          } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
          }
          qrcode.decode(url)
          qrcode.callback = function(imgMsg) {
            if(imgMsg == 'error decoding QR Code' || imgMsg == 'Failed to load the image'
            || imgMsg == 'Couldn\'t find enough finder patterns (found 0)'
            || imgMsg.startsWith('http')) {
              reject(new Error('二维码识别失败，请手动输入'))
            } else {
              resolve(imgMsg)
            }
          }
        })
      },
      //转base64
      getBase64(data) {
        var that = this;
        return new Promise((resolve, reject) => {
          if (data.type !== 'image/jpeg' && data.type !== 'image/png') {
            that.$toast({
              overlay: true,
              message: '请上传 jpg 格式与png格式的图片',
              duration: 2000
            })
            return false
          } else {
            new Compressor(data, {
              quality: 0.6,
              checkOrientation: false,
              convertSize: 5000000,
              maxHeight: 1024,
              minWidth: 768,
              drew(context, canvas) {
                this.base64Image = canvas.toDataURL('image/jpeg');
                resolve(data.file);
                // 当前上传  选择的图片数组
                const formData = new FormData()
                formData.append('base64', this.base64Image)
                formData.append('tag', 'groupbuy')
                Getupload(formData, {
                  headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                  }
                }).then(res => {
                  that.loadingShow = true;
                  // console.log(res, 'res')
                  if (res.code == '200') {
                    Toast.success('卡券照片上传成功');
                    setTimeout(() => {
                      if (res.data) {
                        that.loadingShow = false;
                        that.bookFrom.activeUrl = that.changeHttpImageUrl(res.data);
                        sessionStorage.setItem('activeUrl', that.bookFrom.activeUrl)
                      }
                    }, 1000);
                  } else {
                    that.$toast({
                      overlay: true,
                      message: '卡券照片上传失败，请联系客服',
                      duration: 2000
                    })
                    that.loadingShow = false;
                  }
                })
              },
              error(err) {
                that.showBrowserTip = true;
                alert('err' + JSON.stringify(err) + err)
                reject();
                that.$toast({
                  overlay: true,
                  message: '请重新选择图片，图片太大了，请联系客服',
                  duration: 3000
                })
              },
            });
          }
        });
      },
      headleCake(item, index) {
        //选择一般蛋糕类型
        this.indexs = index
        if (this.$route.query.type == '6' && this.$route.query.type == '1') {
          var skuIdslist = []
          this.bookFrom.cakelist.map(child => {
            skuIdslist.push({
              skuId: child.skuId,
              imgUrl: child.imageUrl,
              marketName: child.marketName
            })
          })
          this.bookFrom.skuInfos = skuIdslist
        } else {
          this.bookFrom.skuInfos = [{
            skuId: item.skuId,
            imgUrl: item.imageUrl,
            marketName: item.marketName
          }]
        }
      },
      handleAddress(item) {
        sessionStorage.setItem('address', item)
      },
      handleUsername(item) {
        sessionStorage.setItem('username', item)
      },
      handlePersonphone(item) {
        sessionStorage.setItem('personphone', item)
      },
      handlePhone(item) {
        sessionStorage.setItem('phone', item)
        if(this.ischecked){
          this.bookFrom.personPhone = this.bookFrom.phone
        }
      },
      handleGreetings(item) {
        sessionStorage.setItem('greetings', this.bookFrom.greetings)
      },
      handleGroupcode(item) {
        sessionStorage.setItem('groupcode', this.bookFrom.groupcode)
      },
      handleRemarks(item) {
        sessionStorage.setItem('remark', this.bookFrom.remarks)
      },
      // 团购通用链接下单--------------------------------------------------------------------------------------------------------
      headlesearchcake() {
          this.showSoldOut = false
        // 点击搜索让 其中选中的蛋糕款式变空
        this.bookFrom.skuInfos.length = 0
        this.indexs2 = -1;
        //通用查询蛋糕

        // 添加CITYID
        console.log(sessionStorage.getItem('deptId'))
        const params = {
          name: this.searchcake,
          id: this.$route.query.id,
          cityId: sessionStorage.getItem('deptId')
        }
        this.isShowAddMore = false
        if (this.searchcake) {
          var that = this;
          getGoodsListByName(params).then(res => {
          if (res.data && res.data.length > 0) {
                this.showSoldOut = false
            this.bookFrom.cakelist = that.changeHttpImageUrlWithArray(res.data)
              if( this.bookFrom.cakelist.length >= 9 ) {
                  this.isShowAddMore = true
                  this.newArrayCakeList = this.bookFrom.cakelist;  //存储数组
                  this.bookFrom.cakelist = this.bookFrom.cakelist.slice(0,9) //修改数组
                }
                this.nextcakelist = this.bookFrom.cakelist[0]
              } else {
                  this.showSoldOut = true
                  this.bookFrom.cakelist = []
                this.searchcake = '';
                return false
              }
            })
        } else {
          this.getByIdForCacheList()
        }
      },
      // 加载更多摁钮
      addMoreList () {
        this.addStartNum = this.addStartNum + this. addStep
        if ( this.addStartNum >= this.newArrayCakeList.length ) {
          this.addStartNum = this.newArrayCakeList.length
          this. isShowAddMore = false
        }
        this.bookFrom.cakelist = this.newArrayCakeList.slice(0,this.addStartNum)
      },
      headleCakety(item, index2) {
        //选择通用蛋糕类型
        this.indexs2 = index2
        this.nextcakelist = item
        this.bookFrom.skuInfos = [{
          skuId: item.skuId,
          imgUrl: item.imageUrl,
          marketName: item.marketName
        }]
      },
      onCancel() {
          this.showSoldOut = false
        this.indexs2 = -1
        // 取消事件
        this. searchcake = '';
        this. addStartNum = 9;
        this. isShowAddMore = false
        // 添加CITYID
        console.log(sessionStorage.getItem('deptId'))
        const params = {
          name: this.searchcake,
          cityId: sessionStorage.getItem('deptId')
        }
        if (this.searchcake) {
          var that = this;
          getGoodsListByName(params).then(res => {
            if (res.data && res.data.length > 0) {
              this.bookFrom.showMore = false;
              this.bookFrom.cakelist = that.changeHttpImageUrlWithArray(res.data)
              this.nextcakelist = this.bookFrom.cakelist[0]
            } else {
              this.$toast({
                overlay: true,
                message: '抱歉，主人，没有搜索到相应的商品',
                duration: 1000
              })
              this.searchcake = '';
              return false
            }
          })
        } else {
          this.getByIdForCacheList()
        }
        this.nextcakelist = [];
        this.bookFrom.skuInfos = [

        ];
      },
      nextstep() {
        this.handleSelectTimeByName()
        if (this.bookFrom.deliveryArea == '') {
          this.$toast({
            overlay: true,
            message: '请选择配送地址',
            duration: 2000
          })
          return false
        } else if (this.bookFrom.address == '') {
          this.$toast({
            overlay: true,
            message: '请输入收货详细地址',
            duration: 2000
          })
          return false
        } else if (this.searchcake == '' && (this.nextcakelist == undefined || this.nextcakelist == null)) {
          this.bookFrom.skuInfos = [];
          this.showstyle = true;
          return false
        } else if (this.bookFrom.skuIds == '') {
          this.$toast({
            overlay: true,
            message: '请选择蛋糕款式',
            duration: 2000
          })
          return false
        } else if (this.bookFrom.orderchannel == '') {
          this.$toast({
            overlay: true,
            message: '请选择购买平台',
            duration: 2000
          })
          return false
        } else if (this.bookFrom.skuInfos.length == 0) {
          this.showstyle = true;
        } else {
          this.currentshow = false
          this.nextstepshow = true
        }
        sessionStorage.setItem('indexs2', this.indexs2)
        sessionStorage.setItem('indexs', this.indexs)
        sessionStorage.setItem('bookFrom.cakelist', JSON.stringify(this.bookFrom.cakelist))
        sessionStorage.setItem('nextcakelist', JSON.stringify(this.nextcakelist))
        sessionStorage.setItem('bookFrom.skuInfos', JSON.stringify(this.bookFrom.skuInfos))
      },
      handleSelectTimeByName() {
        if (this.bookFrom.skuInfos) {
          const cakeInfo = this.bookFrom.skuInfos[0]
          if (cakeInfo.marketName.includes('提前3天')) {
            this.bookFrom.extractstartTimes = ''
            this.minDate = new Date(this.dayjs().add(3, 'day'))
          } else {
            this.minDate = new Date()
          }
        }
      },
      preSetp() {
        this.currentshow = true
        this.nextstepshow = false
      },
      //提交订单--------------------------------------------
      orderSumbit(item) {
        const errorMsg = this.validateFormMessage(item)
        if (errorMsg) {
          this.$toast({
            overlay: true,
            message: errorMsg,
            duration: 2000
          })
          // _czc.push('_setCustomVar','提交失败','提交失败记录')
          return false
        }
        
        var receiverAddress = item.deliveryArea + '/' + item.address
        const params = {
          skuInfos: item.skuInfos,
          receiverAddress: receiverAddress, //收货地址
          longitude: item.longitude, //经度
          latitude: item.latitude, //纬度
          deliveryWay: 2,
          selfDeliveryId: item.selfDeliveryId,
          receiverPhone: item.phone, //电话
          bookerPhone: item.personPhone, // 下单手机号
          receiverName: item.username, //收货人
          channelId: item.channelId, //渠道ID
          blessings: item.greetings, //祝福语
          deliveryDate: item.extractstartTimes, //开始时间
          deliveryTimeSlot: item.extractendTimes, //时间段
          platformOrderId: item.groupcode, //券码
          consumerRemark: item.remarks, //客户备注
          qrCodeUrl: item.activeUrl || '', //二维码地址
          linkType: this.$route.query.type
        }
        if (this.isTryCake) {
          var quantity = item.quantity && item.quantity!='' ?  item.quantity + ' ' : '';
          var _name= item.name && item.name!='' ? item.name+ ' ' : '';
          params.consumerRemark = quantity + _name + item.remarks
        }
        const preparams = {
          deliveryDate: item.extractstartTimes,
          selfDeliveryId: item.selfDeliveryId,
          cityName: item.cityname,
          longitude: item.longitude, //经度
          latitude: item.latitude, //纬度
          deptId: this.deptId,
        }
        getpreSubmitOrder(preparams).then(res => {
          if (res.code == '200') {
            if (params.skuInfos.length == 0) {
              Dialog.alert({
                message: '请挑选蛋糕款式',
                theme: 'round-button',
              }).then(() => {
                // on close
              });
              return false

            } else {
              this.loadingstyleshow = true
              submitOrder(params).then(respose => {
                if (respose.code == '200') {
                  // _czc.push('_setCustomVar','提交成功','提交成功记录')
                  // _czc.push('_setCustomVar','时间统计','提交耗时', localStorage.getItem('times')) // 关于友盟统计的
                  this.loadingstyleshow = false;
                  this.submitshow = true
                  this.orderID = respose.data
                  setCookie('phone', respose.data, 7) //保存cookie(如不设置时间，浏览器关闭后cookie失效)
                  this.removeCache()
                } else {
                  this.$toast({
                    overlay: true,
                    message: respose.msg,
                    duration: 2000
                  })
                  this.loadingstyleshow = false;
                }
              })
            }
          }
          if (res.code == '400') {
            this.tips = res.msg
            this.DeliveryAreashow = true
            this.bookFrom.extractendTimes = ''
          }
        })
      },
      // 校验表单
      validateFormMessage(item) {
        var reg = 11 && /^((11|12|13|14|15|17|18|16|19)[0-9]{1}\d{8})$/;
        if (!item.deliveryArea) {
          return '请选择配送地址'
        }
        if( !item.personPhone ) {
          return '请选择输入下单人电话号'
        } else if (!reg.test(item.personPhone)) {
          return '下单人电话号格式不正确'
        }
        if (!item.address) {
          return '请输入收货详细地址'
        }
        if (!item.username) {
          return '请输入收货人姓名'
        }
        if (!item.phone) {
          return '请输入收货人电话'
        } else if (!reg.test(item.phone)) {
          return '收货人手机号格式不正确'
        }
        if (!item.extractstartTimes) {
          return '请选择配送日期'
        }
        if (!item.extractendTimes) {
          return '请选择配送时间段'
        }
        if (!item.orderchannel) {
          return '请选择购买平台'
        }
        if (!item.groupcode) {
          return '请输入券码'
        }
        // 内部试吃
        if (this.linkType == 100 && item.name == '' && this.isTryCake) {
          return '请选择试吃蛋糕'
        }
        if (!item.activeUrl) {
          return '请上传卡券照片（电子码/二维码的截图）'
        }
      },
      // 清除缓存
      removeCache() {
        sessionStorage.removeItem('city')
        sessionStorage.removeItem('deptId')
        sessionStorage.removeItem('deliveryArea')
        sessionStorage.removeItem('address')
        sessionStorage.removeItem('personphone')
        sessionStorage.removeItem('username')
        sessionStorage.removeItem('phone')
        sessionStorage.removeItem('longitude')
        sessionStorage.removeItem('latitude')
        sessionStorage.removeItem('extractstartTimes')
        sessionStorage.removeItem('extractendTimes')
        sessionStorage.removeItem('channelId')
        sessionStorage.removeItem('orderchannel')
        sessionStorage.removeItem('greetings')
        sessionStorage.removeItem('groupcode')
        sessionStorage.removeItem('remark')
        sessionStorage.removeItem('activeUrl')
        sessionStorage.removeItem('indexs')
        sessionStorage.removeItem('indexs2')
        sessionStorage.removeItem('bookFrom.cakelist')
        sessionStorage.removeItem('bookFrom.skuInfos')
        sessionStorage.removeItem('nextcakelist')
      },
      watchorder() {
        //订单提交后查看订单
        this.$router.push({
          path: '/about',
          query: {
            //传参
            id: this.$route.query.id,
            type: this.$route.query.type,
            channel: this.$route.query.channel,
            orderID: this.orderID,
          }
        })
      },
      upgradeService() {
        window.location.href = 'https://j.youzan.com/qSc_x1'
      },
      // 查看指引
      guidelink() {
        this.guidelinkshow = true;
      },
      activeheadleBack() {
        this.guidelinkshow = false;
      },
      handleshowstyleBtn() {
        this.showstyle = false
      },
      showChannelItem(item) {
        return item.value.includes(this.orderChannelKeyword)
      }
    }
  }
</script>
<style lang='scss'>
@import '@/assets/css/home';
.personCall{
  padding-bottom: 30px;
}
.checked-box{
  margin-left: 10px;
  transform: translateY(-25px);
}

.showImage{
  width: 100%;
  background-size:cover ;
  img{
    width: 100%;
  }
}
.teepTop{
  opacity: .8;
  position: fixed;
  right: 20px;
  bottom: 200px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
